package cn.liujianbo.easycode.common;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.util.Collections;
import java.util.List;

/**
 * @author 刘建波
 * @date 2022-05-25 10:41
 */
@ApiModel("分页对象VO")
@Data
public class PageVO<T> {

    @ApiModelProperty("数据")
    private List<T> records = Collections.emptyList();

    @ApiModelProperty("数据总数")
    private Integer total;

    @ApiModelProperty("每页条数")
    private Integer size;

    @ApiModelProperty("当前页")
    private Integer current;

    @ApiModelProperty("总页数")
    private Integer totalPage;

    /**
     * mybatis plus 分页对象转换为 RPageVO
     *
     * @param page mybatis plus 分页结果对象
     * @param <T>  泛型
     * @return RPageVO
     */
    public static <T, V> PageVO<T> of(Page<V> page, Class<T> clazz) {
        PageVO<T> pageVO = new PageVO<>();
        long total = page.getTotal();
        long size = page.getSize();

        pageVO.setRecords(BeanUtil.copyToList(page.getRecords(), clazz));
        pageVO.setTotal(Math.toIntExact(total));
        pageVO.setSize(Math.toIntExact(size));
        pageVO.setTotalPage(Math.toIntExact(total % size > 0 ? total / size + 1 : total / size));
        pageVO.setCurrent(Math.toIntExact(page.getCurrent()));
        return pageVO;
    }
}
